﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
using Ninject.Modules;
using Sendz.Model;

namespace Sendz.WebUI.Infrastructure
{
    public class NinjectControllerFactory : DefaultControllerFactory
    {
        // A Ninject "kernel" is the thing that can supply object instances
        private readonly IKernel kernel = new StandardKernel(new SendzServices());

        // ASP.NET MVC calls this to get the controller for each request
        protected override IController GetControllerInstance(RequestContext context, Type controllerType)
        {
            if (controllerType == null)
                return null;
            return (IController)kernel.Get(controllerType);
        }

        // Configures how abstract service types are mapped to concrete implementations
        private class SendzServices : NinjectModule
        {
            public override void Load()
            {
                Bind<IUserRepository>().To<EntityUserRepository>(); // Connection string etc. could be passed if needed
                Bind<IIdentityRepository>().To<EntityIdentityRepository>();
                Bind<IFormRepository>().To<EntityFormRepository>();
                Bind<IAutoResponderRepository>().To<EntityAutoResponderRepository>();
            }
        }
    }

    // Ref: http://stackoverflow.com/questions/2963611/how-can-you-inject-an-asp-net-mvc2-custom-membership-provider-using-ninject
    public static class NinjectHelper
    {
        public static readonly IKernel Kernel = new StandardKernel(new SendzServices());

        private class SendzServices : NinjectModule
        {
            public override void Load()
            {
                Bind<IUserRepository>().To<EntityUserRepository>(); // .WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["FooDb"].ConnectionString);
            }
        }
    }
}